package at.fhv.androideightpuzzle.application;

import java.util.Date;

import at.fhv.androideightpuzzle.application.interfaces.IPlayPuzzleController;
import at.fhv.androideightpuzzle.domain.EightPuzzle;
import at.fhv.androideightpuzzle.domain.Position;
import at.fhv.androideightpuzzle.domain.SwapDirection;
import at.fhv.androideightpuzzle.puzzles.PuzzleLoader;

public class PlayPuzzleController implements IPlayPuzzleController{
	
	private EightPuzzle m_eightPuzzle;
	private Date m_start;
	
	public PlayPuzzleController(){
		m_eightPuzzle=null;
	}
	
	public void cancelPuzzle(){
		//
	}
	
	public boolean isFinished(){
		if(m_eightPuzzle!=null){
			return m_eightPuzzle.isFinished();
		}else{
			return false;
		}
	}
	
	public void loadPuzzle(String puzzleId){
		if((puzzleId!=null) && (puzzleId.equals("")==false)){
			m_eightPuzzle=PuzzleLoader.loadPuzzleById(puzzleId);
		}
	}
	
	public void shuffle(){
		if(m_eightPuzzle!=null){
			m_eightPuzzle.shuffle();
		}
	}
	
	public void start(){
		m_start=new Date();
	}
	
	public int[][] swapEmptyPart(SwapDirection swapDirection){
		if(m_eightPuzzle!=null){
			return m_eightPuzzle.swapEmptyPart(swapDirection);
		}else{
			return null;
		}
	}
	
	public int[][] swapPart(Position position){
		if(m_eightPuzzle!=null){
			return m_eightPuzzle.swapPart(position);
		}else{
			return null;
		}
	}
	
	public long getDuration(){
		if(m_start!=null){
			return ((new Date().getTime()-m_start.getTime())/1000);
		}else{
			return -1;
		}
	}
	
	public int[] getEndStateAsArray(){
		return m_eightPuzzle.getEndState();
	}
	
	public int[][] getImagePositions(){
		if(m_eightPuzzle!=null){
			return m_eightPuzzle.getState();
		}else{
			return null;
		}
	}
	
	public int[] getStateAsArray(){
		int[][] stateMatrix=m_eightPuzzle.getState();
		int[] stateArray=new int[9];
		
		int col=0;
		int row=0;
		
		while(row<3){
			stateArray[(row*3+col)]=stateMatrix[row][col];
			
			//matrix shift
			col++;
			
			if(col>=3){
				col=0;
				row++;
			}
		}
		
		return stateArray;
	}
	
	protected EightPuzzle getEightPuzzle(){
		return m_eightPuzzle;
	}
	
	protected void setEightPuzzle(EightPuzzle puzzle){
		if(puzzle!=null){
			m_eightPuzzle=puzzle;
		}
	}
}
